package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserManagementService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 用户管理
 */

@RestController
@RequestMapping("/userManagement")
public class UserManagementController {

    @Reference
    private UserManagementService userManagementService;
    
    //1.新增用户
    @RequestMapping("/add")
    public Result add(@RequestBody Map map, Integer[] roleIds){
        try{
            userManagementService.add(map,roleIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "新增用户失败！");//新增失败
        }
        return new Result(true,"新增用户成功！");//新增成功
    }
    
    //2.分页(条件)查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userManagementService.pageQuery(queryPageBean);
    }
    
    //3.1根据ID查询用户
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            User user= userManagementService.findById(id);
            return new Result(true,"查询用户成功!",user);//查询成功
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"查询用户失败!");//查询失败
        }
    }
    
    //3.2根据用户ID查询用户包含的多个角色ID
    @RequestMapping("/findRoleIdsByUserId")
    public Result findPermissionIdsByRoleId(Integer id){
        try{
            List<Integer> permissionIds = userManagementService.findRoleIdsByUserId(id);
            return new Result(true,"查询用户与角色成功！",permissionIds);//查询成功
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"查询用户与角色失败！");//查询失败
        }
    }


    //3.3编辑用户
    @RequestMapping("/edit")
    public Result edit(@RequestBody Map map,Integer[] roleIds){
        try{
            userManagementService.edit(map,roleIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, "编辑用户失败！");//编辑失败
        }
        return new Result(true,"编辑用户成功！");//编辑成功
    }


    //4.删除用户；
    @RequestMapping("/deleteById")
    public Result deleteById(Integer id){
    
        try{
            userManagementService.deleteAssocication(id);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"删除用户失败！");//删除失败
        }
        return  new Result(true,"删除用户成功！");//删除成功
    }

}
